package com.xxgg.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxgg.common.exception.ApiException;
import com.xxgg.common.exception.Asserts;
import com.xxgg.system.mapper.RoleMenuMapper;
import com.xxgg.system.model.po.Menu;
import com.xxgg.system.mapper.MenuMapper;
import com.xxgg.system.model.po.RoleMenu;
import com.xxgg.system.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 先谢郭嘉
 * @since 2023-01-31 04:33:29
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    MenuMapper menuMapper;
    @Resource
    RoleMenuMapper roleMenuMapper;

    @Override
    public List<Menu> getMenuListByRole(Integer roleId) {
        return menuMapper.getMenuListByRole(roleId);
    }

    @Override
    public List<Menu> menuTree() {
        List<Menu> menuList = menuMapper.selectList(null);
        // 构建地区树
        Menu menuTree = new Menu(menuList);
        return menuTree.buildTree();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteMenu(String menuId) throws ApiException {
        // 删除菜单
        long count = menuMapper.deleteById(menuId);
        Asserts.isFalse(count > 0, "删除菜单失败！");

        // 删除菜单和角色的关联关系
        count = roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>()
                .eq(RoleMenu::getMenuId, menuId));
        Asserts.isFalse(count > 0, "删除菜单关联关系失败！");
        return count > 0;
    }
}
